﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.SessionState;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.Utilities;
using Pap.Data;

namespace Pap.Web.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class ImageRoutingHandler : IRouteHandler, IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 
        /// </summary>
        IImageRepository _Repo;

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageRoutingHandler"/> class.
        /// </summary>
        public ImageRoutingHandler()
        {
            _Repo = ServiceLocator.Current.GetInstance<IImageRepository>();
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            int height = GetHeight(context);
            int width = GetWidth(context);

            if (!string.IsNullOrEmpty(context.Request.QueryString["ImageID"]))
            {
                byte[] imageData = GetImageByID(context);
                SendImage(context, height, width, imageData);
            }
            else
            {
                string path = context.Request.QueryString["Path"];
                SendImage(context, height, width, Bitmap.FromFile(path));
            }
        }

        /// <summary>
        /// Sends the image.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="height">The height.</param>
        /// <param name="width">The width.</param>
        /// <param name="imageData">The image data.</param>
        private void SendImage(HttpContext context, int height, int width, byte[] imageData)
        {
            System.Drawing.Image image = new Bitmap(new MemoryStream(imageData));
            image = SendImage(context, height, width, image);
        }

        /// <summary>
        /// Sends the image.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="height">The height.</param>
        /// <param name="width">The width.</param>
        /// <param name="image">The image.</param>
        /// <returns></returns>
        private System.Drawing.Image SendImage(HttpContext context, int height, int width, System.Drawing.Image image)
        {
            image = ResizeImage(image, height, width);

            context.Response.ContentType = "image/jpeg";
            image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            return image;
        }

        /// <summary>
        /// Gets the image by ID.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private byte[] GetImageByID(HttpContext context)
        {
            Guid imageID = context.Request.QueryString["ImageID"].ToGuid();
            IImage image = _Repo.GetImage(imageID);
            if (image == null)
                image =
                    RegistryInfo.Images.SelectMany(keyvalpair => keyvalpair.Value).SingleOrDefault(
                        i => i.ImageID == imageID);

            if (image == null)
                throw new ArgumentException("Image Id is not valid", "ImageID");

            return image.ImageData;
        }

        /// <summary>
        /// Gets the width.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private static int GetWidth(HttpContext context)
        {
            int width = string.IsNullOrEmpty(context.Request.QueryString["Width"]) ? 100 : context.Request.QueryString["Width"].ToInt32();
            return width;
        }

        /// <summary>
        /// Gets the height.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private static int GetHeight(HttpContext context)
        {
            int height = string.IsNullOrEmpty(context.Request.QueryString["Height"]) ? 75 : context.Request.QueryString["Height"].ToInt32();
            return height;
        }

        /// <summary>
        /// Resizes the image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="height">The height.</param>
        /// <param name="width">The width.</param>
        /// <returns></returns>
        private System.Drawing.Image ResizeImage(System.Drawing.Image image, int height, int width)
        {
            if (width == 100 && height == 75)
                return image.GetThumbnailImage(width, height, delegate() { return false; }, IntPtr.Zero);
            else return image;
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        ///   </returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Gets the HTTP handler.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <returns></returns>
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new ImageRoutingHandler();
        }
    }
}
